package com.jy.modules.cims.common.controller;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jodd.util.StringUtil;

import org.apache.commons.fileupload.FileItem;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSON;
import com.jy.modules.cims.buyback.service.BuyBackImpService;
import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.exception.CimsExceptionConstant;
import com.jy.modules.cims.common.exception.SysAssistException;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.component.common.service.TCMmAgreementService;
import com.jy.modules.cims.component.common.service.TCMmContractService;
import com.jy.modules.cims.component.common.service.TCMmCooperorgService;
import com.jy.modules.cims.component.common.service.TCMmExcelDictionaryService;
import com.jy.modules.cims.component.common.service.TCMmExcelTemplateService;
import com.jy.modules.cims.component.common.service.TCMmTemplateFieldService;
import com.jy.modules.cims.component.sysAssist.ExportAndImport;
import com.jy.modules.cims.data.common.dto.TCMmAgreementDTO;
import com.jy.modules.cims.data.common.dto.TCMmContractDTO;
import com.jy.modules.cims.data.common.dto.TCMmCooperorgDTO;
import com.jy.modules.cims.data.common.dto.TCMmCooperorgDealDTO;
import com.jy.modules.cims.data.common.dto.TCMmExcelDictionaryDTO;
import com.jy.modules.cims.data.common.dto.TCMmExcelTemplateDTO;
import com.jy.modules.cims.data.common.dto.TCMmTemplateFieldDTO;
import com.jy.modules.cims.data.dto.CreditDetailDto;
import com.jy.modules.cims.data.dto.DealDetailByCreditDto;
import com.jy.modules.cims.data.dto.DealDto;
import com.jy.modules.cims.data.dto.LoanDetailDto;
import com.jy.modules.cims.deal.service.DealService;
import com.jy.modules.cims.deal.service.LoanDealService;
import com.jy.modules.cims.deal.service.TransferConfirmService;
import com.jy.modules.cims.interact.IInteractAssist;
import com.jy.modules.cims.settle.service.CreditRedemptionService;
import com.jy.platform.api.org.SessionAPI;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;

/**
 * @classname: CimsModelTemplateController
 * @description: 定义 模板配置
 * @author:
 */
@Controller
@Scope("prototype")
@RequestMapping("/cimsCascade")
public class CimsModelTemplateController extends CimsBaseController {
	private static final Logger logger = LoggerFactory.getLogger(CimsModelTemplateController.class);

	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmCooperorgService")
	private TCMmCooperorgService serviceCooperorg;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmContractService")
	private TCMmContractService serviceContract;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmAgreementService")
	private TCMmAgreementService serviceAgreement;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmTemplateFieldService")
	private TCMmTemplateFieldService serviceTemplate;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmExcelDictionaryService")
	private TCMmExcelDictionaryService serviceExcelDictionary;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmExcelTemplateService")
	private TCMmExcelTemplateService serviceExcelTemplate;

	@Autowired
	@Qualifier("com.jy.modules.cims.deal.service.DealService")
	private DealService dealService;

	@Autowired
	@Qualifier("com.jy.modules.cims.settle.service.CreditRedemptionService")
	private CreditRedemptionService creditRedemptionService;

	@Autowired
	@Qualifier("com.jy.modules.cims.deal.service.LoanDealService")
	private LoanDealService loanDealService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.sysAssist.ExportAndImport")
	private ExportAndImport<?> exportAndImportService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.interact.CInteractAssist")
	public IInteractAssist iInteractAssist;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.deal.service.TransferConfirmService")
	private TransferConfirmService transferConfirmService;

    @Autowired
    private SessionAPI sessionAPI;
    
	@Autowired
	@Qualifier("com.jy.modules.cims.buyback.service.BuyBackImpService")
	private BuyBackImpService buyBackImpService;
    
	
	/**
	 * 
	 * @Title queryListTCMmCooperorg
	 * @Description 查询合作机构信息
	 * @param request
	 * @param response
	 * @param dto
	 * @param dataMsg
	 * @throws Exception
	 *             void
	 * @date 2015-1-22-上午11:17:48
	 * @update
	 * @throws
	 */
	@RequestMapping(value = "/queryListCimsCascadeCooperorg")
	@ResponseBody
	public DataMsg queryListTCMmCooperorg(HttpServletRequest request, HttpServletResponse response, TCMmCooperorgDTO dto,
			@ModelAttribute DataMsg dataMsg) throws Exception {

		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);

		List<TCMmCooperorgDTO> list = serviceCooperorg.searchTCMmCooperorg(params.getSearchParams());
		dataMsg = this.initDataMsg(dataMsg);
		dataMsg.setData(list);
		return dataMsg;
	}

	/**
	 * 
	 * @Title queryListTCMmContract
	 * @Description 查询合约信息
	 * @param request
	 * @param response
	 * @param dto
	 * @param dataMsg
	 * @throws Exception
	 *             void
	 * @date 2015-1-22-上午11:17:25
	 * @update
	 * @throws
	 */
	@RequestMapping(value = "/queryListCimsCascadeContract")
	@ResponseBody
	public DataMsg queryListTCMmContract(HttpServletRequest request, HttpServletResponse response, TCMmContractDTO dto,
			@ModelAttribute DataMsg dataMsg) throws Exception {

		Map<String, Object> searchParams = new HashMap<String, Object>();
		String cooperorgCode = request.getParameter("cooperorgCode");
		dto.setCooperorgCode(cooperorgCode);
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);

		List<TCMmContractDTO> list = serviceContract.searchTCMmContract(params.getSearchParams());

		dataMsg = this.initDataMsg(dataMsg);
		dataMsg.setData(list);
		return dataMsg;
	}
	
	/**
	 * 
	 * @Title queryListTCMmContract
	 * @Description 查询协议信息
	 * @param request
	 * @param response
	 * @param dto
	 * @param dataMsg
	 * @throws Exception
	 *             void
	 * @date 2015-1-22-上午11:17:25
	 * @update
	 * @throws
	 */
	@RequestMapping(value = "/queryListCimsCascadeAgreement")
	@ResponseBody
	public DataMsg queryListCimsCascadeAgreement(HttpServletRequest request, HttpServletResponse response, TCMmAgreementDTO dto,
			@ModelAttribute DataMsg dataMsg) throws Exception {

		Map<String, Object> searchParams = new HashMap<String, Object>();
		String cooperorgCode = request.getParameter("cooperorgCode");
		dto.setCooperorgCode(cooperorgCode);
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);

		List<TCMmAgreementDTO> list = serviceAgreement.searchTCMmAgreement(params.getSearchParams());

		dataMsg = this.initDataMsg(dataMsg);
		dataMsg.setData(list);
		return dataMsg;
	}

	/**
	 * 
	 * @Title queryListTCMmContract
	 * @Description 查询合约信息
	 * @param request
	 * @param response
	 * @param dto
	 * @param dataMsg
	 * @throws Exception
	 *             void
	 * @date 2015-1-22-上午11:17:25
	 * @update
	 * @throws
	 */
	@RequestMapping(value = "/queryListCimsCascadeContracts")
	@ResponseBody
	public DataMsg queryListTCMmContracts(HttpServletRequest request, HttpServletResponse response, TCMmContractDTO dto,
			@ModelAttribute DataMsg dataMsg) throws Exception {

		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);

		List<TCMmContractDTO> list = serviceContract.searchTCMmContractByPaging(params.getSearchParams());

		dataMsg = this.initDataMsg(dataMsg);
		dataMsg.setData(list);
		return dataMsg;
	}

	/**
	 * 
	 * @Title queryListExportFields
	 * @Description 模板导出债权动态字段
	 * @param request
	 * @param response
	 * @param dto
	 * @param dataMsg
	 * @throws Exception
	 *             void
	 * @date 2015-1-22-上午11:37:12
	 * @update
	 * @throws
	 */
	@RequestMapping(value = "/queryListCreditDetailTemplateExportFields")
	@ResponseBody
	public DataMsg queryListCreditDetailExportFields(HttpServletRequest request, HttpServletResponse response, TCMmTemplateFieldDTO dto,
			@ModelAttribute DataMsg dataMsg) throws Exception {

		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);

		List<TCMmTemplateFieldDTO> list = serviceTemplate.searchTCMmCreditDetailTemplateField(params.getSearchParams());

		dataMsg = this.initDataMsg(dataMsg);
		dataMsg.setData(list);
		return dataMsg;
	}

	/**
	 * 
	 * @Title queryListExportFields
	 * @Description 模板导出贷款动态字段
	 * @param request
	 * @param response
	 * @param dto
	 * @param dataMsg
	 * @throws Exception
	 *             void
	 * @date 2015-1-22-上午11:37:12
	 * @update
	 * @throws
	 */
	@RequestMapping(value = "/queryListLoanDetailTemplateExportFields")
	@ResponseBody
	public DataMsg queryListLoanDetailExportFields(HttpServletRequest request, HttpServletResponse response, TCMmTemplateFieldDTO dto,
			@ModelAttribute DataMsg dataMsg) throws Exception {

		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);

		List<TCMmTemplateFieldDTO> list = serviceTemplate.searchTCMmLoanDetailTemplateField(params.getSearchParams());

		dataMsg = this.initDataMsg(dataMsg);
		dataMsg.setData(list);
		return dataMsg;
	}
	

	/**
	 * 
	 * @Title SaveListExportFields
	 * @Description 保存模板信息
	 * @param request
	 * @param response
	 * @param dto
	 * @param dataMsg
	 * @throws Exception
	 *             void
	 * @date 2015-1-23-下午3:24:10
	 * @update
	 * @throws
	 */
	@RequestMapping(value = "/saveListTemplateExportFields")
	@ResponseBody
	public DataMsg SaveListExportFields(HttpServletRequest request, HttpServletResponse response, TCMmExcelDictionaryDTO templateField,
			TCMmExcelTemplateDTO templateDetail, @ModelAttribute DataMsg dataMsg) throws Exception {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		String model = this.getParameterString("model");
		searchParams.put("templateField", templateField);
		searchParams.put("templateDetail", templateDetail);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);

		dataMsg = new DataMsg();
		try {
			if(model.equals("update")){
				templateField.setId(null);
				serviceExcelDictionary.updateTCMmExcelDictionary(templateField);
				serviceExcelTemplate.updateTCMmExcelTemplate(templateDetail);
			}else{
				serviceExcelDictionary.insertTCMmExcelDictionary(templateField);
				serviceExcelTemplate.insertTCMmExcelTemplate(templateDetail);
			}
			
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			throw new SysAssistException(CimsExceptionConstant.SAVE_EXCEL_TEMPLATE_FAILED + e);
		}
		return dataMsg;
	}
	
	/**
	 * 验证债权是否导出
	 * @param request
	 * @param response
	 * @param dto
	 * @param dataMsg
	 */
	@RequestMapping(value = "/isNotExportCredit")
	@ResponseBody
	public DataMsg isNotExportCredit(HttpServletRequest request, HttpServletResponse response, DealDetailByCreditDto dto, @ModelAttribute DataMsg dataMsg){
		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		String isNotExport = dealService.getDealDetailList(searchParams);
		
		dataMsg.setMsg(isNotExport);
		return  dataMsg;
	}

	/**
	 * @throws Exception
	 * 
	 * @Title exportData
	 * @Description 数据明细导出
	 * @param request
	 * @param response
	 * @param dto
	 * @param dataMsg
	 *            void
	 * @date 2015-1-22-下午8:46:35
	 * @update
	 * @throws
	 */
	@RequestMapping(value = "/exportDataName")
	public void exportData(HttpServletRequest request, HttpServletResponse response, DealDetailByCreditDto dto, @ModelAttribute DataMsg dataMsg)
			throws Exception {
		// 更新交易流水状态为在途
		TCMmCooperorgDealDTO cooperorgDealDTO = new TCMmCooperorgDealDTO();
		cooperorgDealDTO.setDealCode(dto.getDealCode());
		cooperorgDealDTO.setCooperativeAgencyDealStatus(CimsConstant.DEAL_STATUS_WAY);
		String contractCode = this.getParameterString("contractCode");
		String exportType = this.getParameterString("exportType");
		String templateType = this.getParameterString("creditorAffirmRule");
		String fileName = this.getParameterString("fileName");
	//	String isPlan = this.getParameterString("isPlan");
		// 更新交易流水状态为在途
		dealService.updateDealStatus(cooperorgDealDTO);

		Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("dto", dto);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		FileOutputStream fOutLoan = null;
		FileOutputStream fOut = null;

		//String uploadPath = "";
		try {

			// 债权导出
			if (exportType.equals(CimsConstant.CREDIT_RESOURCE) 
					|| exportType.equals(CimsConstant.REDEMPTION_RESOURCE)
					|| exportType.equals(CimsConstant.BUYBACK_RESOURCE)) {
				List<CreditDetailDto> result = new ArrayList<CreditDetailDto>();
				List<CreditDetailDto> listCredit = dealService.getDealDetailByCreditListForExport(params.getSearchParams());
				if (CollectionsUtils.isNotEmpty(listCredit)) {
					String creditPackageName = this.getParameterString("creditPackage");
					if (null == creditPackageName) {
						creditPackageName = "";
					}
					for (CreditDetailDto creditDetailDto : listCredit) {
						if (null == creditDetailDto.getPackageNum()) {
							creditDetailDto.setPackageNum(creditPackageName);
						}
						result.add(creditDetailDto);
					}
				}

				ExportAndImport<CreditDetailDto> exportAndImport = new ExportAndImport<CreditDetailDto>();
				HSSFWorkbook workbook = exportAndImport.exportExcel(fileName, contractCode, templateType, result);
				fileName = exportAndImport.fileNameOperation(contractCode, templateType);
				write(workbook, fileName, response);
				// 贷款导出
			} else if (exportType.equals(CimsConstant.LOAN_RESOURCE)) {
				List<LoanDetailDto> listLoan = loanDealService.getDealDetailByLoanListForExport(params.getSearchParams());
				ExportAndImport<LoanDetailDto> exportAndImport = new ExportAndImport<LoanDetailDto>();
				HSSFWorkbook workbook = exportAndImport.exportExcel(fileName, contractCode, templateType, listLoan);
				fileName = exportAndImport.fileNameOperation(contractCode, templateType);
				write(workbook, fileName, response);
				// 是否导出还款计划表
//				if (isPlan.equals(CimsConstant.IS_LOAN_COST_PLAN)) {
//					String path = PropertyUtil.get(CimsConstant.LOAN_COST_PLAN_URL);
//					// 上传路径 = path+fileUrl
//					String fileUrl = exportAndImport.fileUrl(contractCode).append(File.separator).toString();
//					String fileUrlLoanName = fileUrl + File.separator + contractCode + CimsConstant.FILE_TYPE;
//					uploadPath = path + fileUrl.toString();
//					File fileLoan = new File(path + fileUrl);
//					if (!fileLoan.exists()) {
//						fileLoan.mkdirs();
//					}
//					fOutLoan = new FileOutputStream(path + fileUrlLoanName);
//					workbook.write(fOutLoan);
//					ExportAndImport<RefundPlanDTO> exportAndImportCodtPlan = new ExportAndImport<RefundPlanDTO>();
//					for (int i = 0; i < listLoan.size(); i++) {
//						LoanDetailDto dtoLoan = listLoan.get(i);
//						String contractNo = dtoLoan.getContractNo();
//						List<RefundPlanDTO> refundPlan = loanDealService.getRefundPlanListByLoan(dtoLoan);
//
//						String fileUrlName = fileUrl + File.separator + contractNo + CimsConstant.FILE_TYPE;
//						HSSFWorkbook workbookCostPlan = exportAndImportCodtPlan.exportExcelCostPlan(fileName, contractNo, dtoLoan, refundPlan);
//
//						fOut = new FileOutputStream(path + fileUrlName);
//						workbookCostPlan.write(fOut);
//						fOut.close();
//					}
//
//				} else 
//					fileName = exportAndImport.fileNameOperation(contractCode, templateType);
//					write(workbook, fileName, response);
//				}
			}

		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			e.printStackTrace();
			throw new SysAssistException(CimsExceptionConstant.EXPORT_EXCEL_FAIL + e.getMessage());
		} finally {
			if (null != fOutLoan) {
				fOutLoan.close();
			}
			if (null != fOut) {
				fOut.close();
			}
		}

//		if (isPlan.equals(CimsConstant.IS_LOAN_COST_PLAN)) {
//			FTPUtils ftp = null;
//			ServletOutputStream servletOutputStream = null;
//			try {
//				ftp = new FTPUtils(orgFtpConfigInfo.getOrg58FtpHostName(), orgFtpConfigInfo.getOrg58FtpPort(), orgFtpConfigInfo.getOrg58FtpUser(),
//						orgFtpConfigInfo.getOrg58FtpPassword());
//				// 登录FTP不成功直接返回
//				if (!ftp.ftpLogin()) {
//					throw new SysAssistException(java.text.MessageFormat.format(CimsExceptionConstant.FTP_LOGIN_FAIL2,
//							new Object[]{orgFtpConfigInfo.getOrg58FtpUser(), orgFtpConfigInfo.getOrg58FtpHostName()}));
//				}
//
//				ExportAndImport<LoanDetailDto> exportAndImport = new ExportAndImport<LoanDetailDto>();
//				String zipFile = exportAndImport.fileUrl(contractCode).toString() + ".zip";
//				String romotUpLoadePath = StringUtils.append(orgFtpConfigInfo.getOrg58FtpDir(),
//						DateTimeUtils.getDateTime(DateTimeUtils.DEFAULT_DATE_FORMAT), "/");
//				String ftpZipFile = romotUpLoadePath + zipFile;
//
//				boolean existsFile = ftp.existsFile(ftpZipFile);
//				logger.info("existsFile:::" + existsFile);
//
//				if (!existsFile) {
//					String localZipFile = uploadPath + zipFile;
//					String success = ZipFileUtils.zip(uploadPath, localZipFile, false);
//					if (null != success) {
//						throw new SysAssistException(success);
//					}
//
//					ftp.uploadFile(new File(localZipFile), romotUpLoadePath);
//				}
//
//				servletOutputStream = response.getOutputStream();
//				response.setContentType("application/x-download charset=UTF-8");
//				response.setHeader("Content-disposition", "attachment;filename=" + zipFile);
//				boolean downloadFlag = ftp.downloadFile(ftpZipFile, servletOutputStream);
//				logger.info("downloadFlag:::" + downloadFlag);
//			} catch (Exception e) {
//				e.printStackTrace();
//				throw new SysAssistException(e.getMessage());
//			} finally {
//				// 退出FTP
//				if (null != ftp) {
//					ftp.ftpLogOut();
//				}
//			}
//		}

	}

	/**
	 * 导入Excel文件
	 * 
	 * @param response
	 * @param request
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/importCreditDetail", method = RequestMethod.POST)
	public void importCreditDetail(HttpServletResponse response, HttpServletRequest request, @ModelAttribute DataMsg dataMsg) throws Exception {
		Writer out = response.getWriter();
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			String contractCode = request.getParameter("contractCode");
			String dealType = this.getParameterString("dealType");
			String exportTypeValue = this.getParameterString("exportTypeValue");
			String dealCode = this.getParameterString("dealCode");
			//包
			String packageNum = this.getParameterString("packageNum");
			String redeemDate = this.getParameterString("redeemDate");
			String cooperorgCode = this.getParameterString("cooperorgCode");
			String agreementCode = this.getParameterString("agreementCode");
			String creditAffiliation = this.getParameterString("creditAffiliation");
			// 获取文件流
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
			FileItem fileItems = file.getFileItem();
			String fileName = fileItems.getName();
			InputStream inputStream = file.getInputStream();

			Class<?> classObject = CreditDetailDto.class;
			// 设置需要进行数据转换的格式,map中的KEY值为fieldName
			Map<String, Map> excelColumnsConvertMap = new HashMap<String, Map>();
			Map<String, String> dealCreditorStatus = new HashMap<String, String>();
			dealCreditorStatus.put("已卖出", "02"); // 已卖出
			dealCreditorStatus.put("取消", "03");
			dealCreditorStatus.put("确认", "05");// 赎回
			
			Map<String, String> settlementSignName = new HashMap<String, String>();
			settlementSignName.put("待结算", "01"); // 待结算
			settlementSignName.put("取消", "00"); // 取消

			excelColumnsConvertMap.put("costState", settlementSignName);
			excelColumnsConvertMap.put("dealCreditorStatus", dealCreditorStatus);

			List<CreditDetailDto> creditDealList = (List<CreditDetailDto>) exportAndImportService.excelImport(inputStream, fileName, contractCode,
					dealType, classObject, excelColumnsConvertMap);
			
			//zhoupeng 债权转让导入时未做条数的限制，应限制1000条 
			if(creditDealList!=null&&creditDealList.size()>1000){
				throw new Exception("导入数据大于1000条，导入失败");
			}
			
			

			logger.info("zhoupcs1 字段exportTypeValue:credit====:" + exportTypeValue);
			// 6.入库操作
			if (exportTypeValue.equals(CimsConstant.CREDIT_RESOURCE)) {//到入来源为 债权
				String popStatus = "ok";
				String popMsg = "";
				if (creditDealList != null && creditDealList.size() > 0) {
					if(!SimpleStringUtils.hasText(creditAffiliation)){
						throw new Exception("月还归属不能为空！请选择月还归属！");
					}
					String userId = String.valueOf(sessionAPI.getCurrentUserInfo().getUserId());
					//查询超时表，向核心重发超时数据
					List<String> timeoutTransNoList = transferConfirmService.queryTimeoutTransNos(new String[]{"4021","4022"});
					for (String confirmTransNo : timeoutTransNoList) {
						try {
							transferConfirmService.doTransferConfirmTimeout(confirmTransNo, creditAffiliation, userId);
						} catch (Exception e) {
							logger.error(e.getMessage(), e);
							popStatus = "error";
							popMsg += "重发超时数据异常," + e.getMessage() + ",前端流水号=" + confirmTransNo + "<p>";
						}
					}

					//导入excel新数据，过滤无效数据，进行转让确认、释放
					try {
						transferConfirmService.doTransferConfirm(creditDealList, cooperorgCode, creditAffiliation, dealCode, userId);
					} catch (Exception e) {
						logger.error(e.getMessage(), e);
						popStatus = "error";
						popMsg += "转让确认/释放异常," + e.getMessage() + ",批次号=" + dealCode;
					}
				} else {
					//导入excel没有记录，不处理
					popStatus = "error";
					popMsg = "导入excel没有记录";
				}
				
				result.put("status", popStatus);
				result.put("errorMassage", popMsg);
			
			} else if (exportTypeValue.equals(CimsConstant.REDEMPTION_RESOURCE)) {
				//赎回
				if(SimpleStringUtils.isEmpty(dealCode)){
					DealDto dealDto = new DealDto();
					dealDto.setCooperorgCode(cooperorgCode);
					dealDto.setAgreementCode(agreementCode);
		         	dealDto.setContractCode(contractCode);
		         	dealDto.setCreditPackageName(packageNum);
//		         	dealDto.setRedemptionDate(DateUtil.getFromString(redeemDate));
		         	
					creditRedemptionService.doImprotCreatRedemption(dealDto,creditDealList);
					result.put("dealCode", dealDto.getDealCode());
					result.put("id", dealDto.getId());
				}else{
					creditRedemptionService.doExcelImportResult(creditDealList, dealCode);
				}
				result.put("status", "ok");
			} else if (exportTypeValue.equals(CimsConstant.BUYBACK_RESOURCE)) {
				//贷款回购
				if (StringUtil.isEmpty(dealCode)) {
					throw new RuntimeException("流水批次号不能为空");
				}
				buyBackImpService.doImportBuyBackExcel(creditDealList, dealCode, redeemDate, contractCode);
				result.put("status", "ok");
			}

			// 7.回显数据
			out.write(JSON.toJSONString(result));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			dataMsg.failed(e.getMessage());
			result.put("status", "error");
			result.put("errorMassage", e.getMessage());
			out.write(JSON.toJSONString(result));
			// throw new
			// Exception(CimsExceptionConstant.IMPORT_EXCEL_FAIL+e.getMessage());
		}
	}

	/**
	 * 导入Excel文件
	 * 
	 * @param response
	 * @param request
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/importCreditSettleBill", method = RequestMethod.POST)
	public void importCreditSettleBill(HttpServletResponse response, HttpServletRequest request, @ModelAttribute DataMsg dataMsg) throws Exception {
		Writer out = response.getWriter();
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			/*String contractCode = request.getParameter("contractCode");
			String dealType = this.getParameterString("dealType");
			String exportTypeValue = this.getParameterString("exportTypeValue");
			String dealCode = this.getParameterString("dealCode");
			//包
			String packageNum = this.getParameterString("packageNum");
			String redeemDate = this.getParameterString("redeemDate");
			String cooperorgCode = this.getParameterString("cooperorgCode");
			String agreementCode = this.getParameterString("agreementCode");*/
			
			// 获取文件流
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
			FileItem fileItems = file.getFileItem();
			String fileName = fileItems.getName();
			InputStream inputStream = file.getInputStream();

			Class<?> classObject = CreditDetailDto.class;
			// 设置需要进行数据转换的格式,map中的KEY值为fieldName
			Map<String, Map> excelColumnsConvertMap = new HashMap<String, Map>();
			Map<String, String> settlementSignName = new HashMap<String, String>();
			settlementSignName.put("待结算", "01"); // 待结算
			settlementSignName.put("取消", "00"); // 取消
			
			Map<String, String> abnormalSettle = new HashMap<String, String>();
			abnormalSettle.put("提前结清", "2"); // 提前结清
			
			excelColumnsConvertMap.put("settlementSignName", settlementSignName);
			excelColumnsConvertMap.put("abnormalSettle", abnormalSettle);
			String BillCode = CimsConstant.CREDIT_SETTLEBILL_CODE;
		    String BillName = CimsConstant.CREDIT_SETTLEBILL_NAME;
		    String Billimport = CimsConstant.CREDIT_SETTLEBILL_ISIMPORT;
			List<CreditDetailDto> creditDealList = (List<CreditDetailDto>) exportAndImportService.excelImportParameter(inputStream, fileName,Billimport, BillCode,
					BillName, classObject, excelColumnsConvertMap);

			// 6.入库操作
			
			//修改   CreditDealDetail 表 结算债权价值  结算标识
	        dealService.updateCreditDealDetailToCostbackFee(creditDealList);
			
			// 7.回显数据
			result.put("status", "ok");
			out.write(JSON.toJSONString(result));
		} catch (Exception e) {
			e.printStackTrace();
			dataMsg.failed(e.getMessage());
			result.put("status", "error");
			result.put("errorMassage", e.getMessage());
			out.write(JSON.toJSONString(result));
			// throw new
			// Exception(CimsExceptionConstant.IMPORT_EXCEL_FAIL+e.getMessage());
		}
	}

	/**
	 * 导入Excel文件
	 * 
	 * @param response
	 * @param request
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/importLoanDetail", method = RequestMethod.POST)
	public void importLoanDetail(HttpServletResponse response, HttpServletRequest request, @ModelAttribute DataMsg dataMsg) throws Exception {
		Writer out = response.getWriter();
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			String contractCode = request.getParameter("contractCode");
			String dealType = this.getParameterString("dealType");
			//String exportTypeValue = this.getParameterString("exportTypeValue");
			//String dealCode = this.getParameterString("dealCode");

			String resultType = this.getParameterString("resultType");
			
			String packageNum = this.getParameterString("packageNum");
			String cooperorgCode = this.getParameterString("cooperorgCode");
			//String agreementCode = this.getParameterString("agreementCode");

			// 获取文件流
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
			FileItem fileItems = file.getFileItem();
			String fileName = fileItems.getName();
			InputStream inputStream = file.getInputStream();
			LoanDetailDto loanDetailDto = new LoanDetailDto();
			Class<?> classObject = loanDetailDto.getClass();
			// 设置需要进行数据转换的格式,map中的KEY值为fieldName
			Map<String, Map> excelColumnsConvertMap = new HashMap<String, Map>();
			Map<String, String> dealLoanStatus = new HashMap<String, String>();
			dealLoanStatus.put("审批通过", "02");
			dealLoanStatus.put("审批拒绝", "03");
			dealLoanStatus.put("放款成功", "04");
			dealLoanStatus.put("放款失败", "05");
			
			Map<String, String> settlementSignName = new HashMap<String, String>();
			settlementSignName.put("待结算", "01"); // 待结算
			settlementSignName.put("取消", "00"); // 取消

			excelColumnsConvertMap.put("costState", settlementSignName);

			excelColumnsConvertMap.put("loanStatus", dealLoanStatus);
			List<LoanDetailDto> loanDetailList = (List<LoanDetailDto>) exportAndImportService.excelImport(inputStream, fileName, contractCode,
					dealType, classObject, excelColumnsConvertMap);
			// 6.入库操作
//			loanDealService.doConfirmLoanImportResult(loanDetailList, resultType);

			/*String busiNoForInteract = iInteractAssist.getBusiNoForInteract();
			loanDealService.doRegisterLoanImportResult(busiNoForInteract, loanDetailList, resultType);
			loanDealService.doLoanExcuteInterface(loanDetailList, busiNoForInteract, resultType);*/
			DealDto dealDto = new DealDto();
			dealDto.setCreditPackageName(packageNum);
			dealDto.setCooperorgCode(cooperorgCode);
			dealDto.setContractCode(contractCode);
			loanDealService.doLoanImportResult(loanDetailList, resultType,dealDto);
			
			// 7.回显数据
			result.put("status", "ok");
			out.write(JSON.toJSONString(result));
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			result.put("status", "error");
			result.put("errorMassage", e.getMessage());
			out.write(JSON.toJSONString(result));
			// throw new
			// Exception(CimsExceptionConstant.IMPORT_EXCEL_FAIL+e.getMessage());
		}
	}

	/**
	 * 页面输出
	 * 
	 * @param workbook
	 * @param fileName
	 * @param response
	 * @throws IOException
	 */
	private void write(HSSFWorkbook workbook, String fileName, HttpServletResponse response) throws IOException {

		try {
			fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8");
			response.setContentType("application/vnd.ms-excel");
			response.setContentType("application/vnd.openxmlformatSs-officedocument.spreadsheetml.sheet");
			response.setCharacterEncoding("UTF-8");
			response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1") + ".xls");
			workbook.write(response.getOutputStream());
			response.getOutputStream().flush();
		} catch (Exception e) {
			throw new SysAssistException(CimsExceptionConstant.EXPORT_EXCEL_FAIL + e.getMessage());
		} finally {
			response.getOutputStream().close();
		}
	}

}
